﻿using KingerRobot.PCRBW.Dao;
using KingerRobot.PCRMES.Spi;
using System.Threading.Tasks;

namespace KingerRobot.PCRBW.Biz;
/// <summary>
/// 滑台1取料验证
/// </summary>
public class ST1TaskBiz : K8.MDCBB.Biz
{
    #region 配置参数
    private ParamData Param { get; set; }

    class ParamData
    {
        /// <summary>
        /// 机台名称
        /// </summary>
        public string EquipName { get; set; }
    }
    #endregion

    #region PLC 通讯参数
    private ValueData Data { get; set; }
    class ValueData
    {
        #region 点位
        /// <summary>
        /// 1#入库滑台状态
        /// </summary>
        public int SlideStatus { get; set; }
        /// <summary>
        /// 1#入库滑台交互标志位
        /// </summary>
        public int CommandFlag { get; set; }
        /// <summary>
        ///  1#入库滑台流水号
        /// </summary>
        public int InSerialNumber { get; set; }
        /// <summary>
        /// 1#入库滑台取圈内径
        /// </summary>
        public int Innerdiameter { get; set; }
        /// <summary>
        /// 1#入库滑台完成任务流水号
        /// </summary>
        public int ReSerialNumber { get; set; }
        /// <summary>
        /// 1#入库滑台裸圈机台允许取圈信号
        /// </summary>
        public int CrossEnd { get; set; }
        /// <summary>
        /// 1#入库有货（滑台到位信号允许龙门取）
        /// </summary>
        public int AllowSignal { get; set; }
       

        
        #endregion
    }
    #endregion

    #region 缓存
    private CacheData Cache { get; set; }
    class CacheData
    {
        public int FinalTaskNo { get; set; }
    }
    #endregion

    #region 实时日志
    private StepData Step { get; set; }
    class StepData
    {
        private string _msg = string.Empty;
        public string StepMsg
        {
            get
            {
                return this._msg;
            }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    this._msg = string.Empty;
                    return;
                }
                this._msg = $"{System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}>>{value}";
            }
        }
    }
    private void StepMsg(string msg)
    {
        this.Step.StepMsg = msg;
        this.WriteLog(msg);
    }
    #endregion

    #region 文件日志（运行需要 Nlog 配置）
    private void WriteLog(string message)
    {
        K8.LSF.Client.Log(new K8.LSF.Log { Data = message });
    }
    #endregion

    /// <summary>
    /// 和 PLC 通讯对象
    /// </summary>
    private BizData BizData { get; set; }
    public int Execute(BizData writer)
    {
        // Excute 方法外使用 BizParam
        this.BizData = writer;
        // 返回参数
        var result = 0;
        string errorMsg = string.Empty;



        if (Data.SlideStatus == (int)EnumGantryStatus.Free && Data.CommandFlag == (int)EnumGantryStatus.Free && Data.CrossEnd == 0)
        {
            this.StepMsg($"滑台入库》{Param.EquipName}号滑台任务清空 入库滑台状态-{Data.SlideStatus};入库滑台交互标志位:{Data.CommandFlag} ;入库有货（滑台到位信号允许龙门取）——十字架1完成信号:{Data.CrossEnd} ");
            //清理任务
            var service = K8.RSF.Client.Create<ISlibeTableService>();
            var task = service.DeleteTask(Param.EquipName);
            
            return result;
        }

        #region 完成任务
        //完成任务

        if (Data.AllowSignal == 1 && Data.InSerialNumber != Cache.FinalTaskNo && Data.InSerialNumber > 0)
        {
            FinishTask(writer);
            return result;
        }
        #endregion

        if (Data.SlideStatus  != (int)EnumGantryStatus.Free )
        {
            this.StepMsg($"滑台入库》{Param.EquipName}号滑台不可写或非空闲状态 GantryStatus-{Data.CommandFlag}");
            return result;
        }
        if (Data.CommandFlag != (int)EnumGantryStatus.Free)
        {
            this.StepMsg($"滑台入库》{Param.EquipName}号标志位为 GantryStatus-{Data.CommandFlag}");
            return result;
        }

        //获取十字架信号和MES信息
        this.StepMsg($"滑台入库》十字架完成信号1:{Data.CrossEnd}");
        //现场产出信号
        if (Data.CrossEnd == 1)
        {
            var service = K8.RSF.Client.Create<ISlibeTableService>();
            var task = service.CreateTask(Param.EquipName, 1);
            if (task == null)
            {
                this.StepMsg($"滑台入库》{Param.EquipName}未创建任务！返回值null");
                return result;
            }
            this.StepMsg($"滑台入库》日志1,返回值任务号:{task.TaskNo}");

            if (task.TaskNo <= 0)
            {
                this.StepMsg($"滑台入库》{Param.EquipName}未创建任务！返回值{task.TaskNo}");
                return result;
            }

            //取料信号传递给滑台 取料  //下发流水号
            var data = this.BizData.WriteData(new
            {
                InSerialNumber1 = task.TaskNo,//任务流水号
                Innerdiameter = task.Innerdiameter,
                CommandFlag = 1
            });

            if (data > 0)
            {
                int flag = service.ExecuteTask(task.TaskNo, 0);
                if (flag <= 0)
                {
                    this.StepMsg($"滑台入库》{Param.EquipName}未下发执行任务！返回值{flag}，任务号：{task.TaskNo}");
                    return result;
                }

                //指令下发取料成功
                this.StepMsg($"滑台入库》滑台{Param.EquipName}指令下发取料成功:{data}");
            }
            else
            {
                this.StepMsg($"滑台入库》滑台{Param.EquipName}指令下发取料失败！");
            }
        }
       
        return result;
    }

    private void FinishTask(BizData writer)
    {
        var taskService = K8.RSF.Client.Create<ISlibeTableService>();
        var finishResult = taskService.FinishTask(Data.InSerialNumber);
        if (finishResult == 1)
        {
            Cache.FinalTaskNo = Data.InSerialNumber;//流水号缓存
            this.StepMsg($"滑台入库》[{Param.EquipName}]滑台,完成任务结束");
        }
    }
}
